package com.tnl.hunter.webchat.controller;

import com.aliyuncs.dyplsapi.model.v20170525.BindAxbResponse;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionResponse;
import com.aliyuncs.exceptions.ClientException;
import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.hunter.service.IOrderService;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.tnl.hunter.webchat.utils.DateUtils;
import com.tnl.hunter.webchat.utils.FileUtils;
import com.tnl.hunter.webchat.utils.SecretAXB;
import com.tnl.hunter.webchat.utils.WxaTemplateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.XWPFConverterException;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OrderController {

	private static final Logger logger = LoggerFactory
			.getLogger(OrderController.class);

	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private HunterCompanyDAO hunterCompanyDAO;
	@Autowired
	private HunterDAO hunterDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private JobDAO jobDAO;
	@Autowired
	private JobTitleDAO roleDAO;
	@Autowired
	private	IOrderService orderService;
	@Autowired
	private EvaluateDAO evaluateDAO;
	@Autowired
	private WxAppUserDAO wxAppUserDAO;
	@Autowired
	private SysConfigRepo sysConfigService;
	@Autowired
	private PersonDAO personDAO;
	@Autowired
	private EmployeeDAO employeeDAO;

	// =================菜单入口 -- 订单详情简历
	/**
	 * 订单详细信息--简历
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrdetailResume.do", method = RequestMethod.GET)
	public String myOrdetailResume(HttpServletRequest request, Model model,Integer orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
//		 openId="o852Is3NXW-0ns6b4e9lzl-6XKbg";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		OrderResume resume=null;
		if(!StringUtils.isEmpty(orderId)){
			resume=orderService.getByOrderId(orderId);
		}else{
			resume=new OrderResume();
		}
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		model.addAttribute("resume", resume);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailResume";
	}

	@OAuthRequired 
	@RequestMapping(value = "wechat/order/uploadResume.do", method = RequestMethod.POST)
	public String uploadResumeFile(HttpServletRequest request,MultipartFile file, ModelMap model,Integer employeeId,Integer hunterId,
			Integer ordescId,Integer id,Integer orderId,String remark) {
		HttpSession session = request.getSession();
		
		String openid = (String) session.getAttribute("OpenId");
		
		logger.debug("openid is " + openid);
		if (StringUtils.isEmpty(openid)) {
			logger.debug("openid is null");
			return "wechat/candidate/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openid);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		Employee emp=employeeDAO.getByEmpId(employeeId);
		//String realPath = request.getSession().getServletContext().getRealPath("/resources/resume");
		//指定路径
		String realPath = FileController.BASE_PATH;
		logger.debug("path is " + realPath);
		String newFileName = null;
		//判断文件不为空的前提下
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();
			String suffix=fileName.substring(fileName.lastIndexOf("."));
			logger.info("ext suffix result="+suffix);
			FileOutputStream fos;
			newFileName=DateUtils.getDate("yyyyMMddHHmm")+"-"+emp.getPersonId()+suffix;//避免冲突
			String filePath=realPath + "/" + newFileName;
			logger.debug(filePath);
			try {
				fos = FileUtils.openOutputStream(new File(filePath));
				IOUtils.copy(file.getInputStream(), fos);
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}//
			FileUtils.uploadFile(filePath, newFileName, WebchatServiceConstant.bucket, 2);//upload file
			//word转换html预览文件2019/02/28
			if(suffix.equals(".doc")){
				try {
					InputStream input = new FileInputStream(new File(filePath));
					HWPFDocument wordDocument = new HWPFDocument(input);
					WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter
							(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
					wordToHtmlConverter.setPicturesManager(new PicturesManager() {
						   public String savePicture(byte[] content, PictureType pictureType,
						     String suggestedName, float widthInches, float heightInches) {
						    return suggestedName;
						   }
						  });
					 wordToHtmlConverter.processDocument(wordDocument);
					  List pics = wordDocument.getPicturesTable().getAllPictures();
					  if (pics != null) {
					   for (int i = 0; i < pics.size(); i++) {
					    Picture pic = (Picture) pics.get(i);
					    try {
					     pic.writeImageContent(new FileOutputStream(filePath
					       + pic.suggestFullFileName()));
					    } catch (FileNotFoundException e) {
					     e.printStackTrace();
					    }
					   }
					  }
					  Document htmlDocument = wordToHtmlConverter.getDocument();
					  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
					  DOMSource domSource = new DOMSource(htmlDocument);
					  StreamResult streamResult = new StreamResult(outStream);
					  TransformerFactory tf = TransformerFactory.newInstance();
					  Transformer serializer;
					  serializer = tf.newTransformer();
					  serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
					  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
					  serializer.setOutputProperty(OutputKeys.METHOD, "html");
					  serializer.transform(domSource, streamResult);
					  outStream.close();
					  String content = new String(outStream.toByteArray());
					  String newHtmlFileName=DateUtils.getDate("yyyyMMddHHmm")+"-"+emp.getPersonId()+".html";//避免冲突
					  //FileUtils.writeStringToFile(new File(filePath, newHtmlFileName), content, "utf-8");
					  FileUtils.uploadFile(new File(filePath),newHtmlFileName,WebchatServiceConstant.bucket, 2, content, "utf-8",false);//upload file
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FactoryConfigurationError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (TransformerConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch (TransformerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(suffix.equals(".docx")){
			    // String filepath = "D:\\Tomcat8.0\\File\\";
		        //String sourceFileName =filepath+"1.docx"; 
				String targetName=DateUtils.getDate("yyyyMMddHHmm")+"-"+emp.getPersonId()+".html";//避免冲突
		        String targetFileName = realPath+targetName+".html"; 
		        String imagePathStr = realPath+"/image/"; 
		
				OutputStreamWriter outputStreamWriter = null; 
		        try { 
		          XWPFDocument document = new XWPFDocument(new FileInputStream(filePath)); 
		          XHTMLOptions options = XHTMLOptions.create(); 
		          // 存放图片的文件夹 
		          options.setExtractor(new FileImageExtractor(new File(imagePathStr))); 
		          // html中图片的路径 
		          options.URIResolver(new BasicURIResolver("image")); 
		          outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "utf-8"); 
		          XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance(); 
		          xhtmlConverter.convert(document, outputStreamWriter, options); 
		        } catch (XWPFConverterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally { 
		          if (outputStreamWriter != null) { 
		            try {
						outputStreamWriter.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
		          } 
		          FileUtils.uploadFile(targetFileName, targetName, WebchatServiceConstant.bucket, 2);//upload file
		        }
			}
		}
		// 更新tb_order_resume信息
		logger.debug("id=="+id);
		OrderResume resume=orderService.getResumeById(id);
		logger.debug("newFilename=="+newFileName);
		logger.debug("resume=="+resume.getId());
		orderService.updOrderResume(newFileName,DateUtils.getDateTime(),resume.getId());
		logger.debug("upload file update1");
		/* 微信 js config */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString().replace("http", "https");
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);

		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);
		/* 微信 js config */
		logger.debug("upload file update2");
		if(newFileName!=null){
			logger.debug("upload file update3");
			//----推送消息会猎---start
			//get order detail
			Order order=orderService.getById(orderId);
			//get hunter detail
			//get orderdesc detail
			OrderDesc desc=orderService.getOrderDescById(ordescId);
			//send msg 会猎服务号--订单状态更新提醒
			String tempjsonhunters = TemplateData
					.New()
					.setTouser(hunter.getOpenid())
					.setTemplate_id("NRCvt7vthW-aNjQFAkHWA2GIQzpxCOC04VdyNA_7yMc")
					.setUrl("https://www.tiaonali.com/tnl-hunter/wechat/order/toOrdetailResume.do?orderId="
							+ order.getId())
					.add("first",
							"您好，用户"+emp.getName()+"预约的「￥"+desc.getSpec()+"/"+desc.getName()+"」项目已上传完成。", "#274084")
					.add("keyword1", WebchatServiceConstant.ORDERCODE+order.getOrdercode(), "#000000")
					.add("keyword2","已完成", "#F47e2d")
					.add("keyword3",order.getCreateTime(), "#000000")
					.add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
					.build();
			System.out.println(tempjsonhunters);
			ApiResult resulthunters = TemplateMsgApi.send(tempjsonhunters);
			logger.info("会猎上传简历，推送消息结果="+resulthunters);
			//send msg 候选人服务--订单状态更新提醒
			String tempjson = TemplateData
					.New()
					.setTouser(emp.getOpenid())
					.setTemplate_id("TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
					.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/candidate/order/myOrdetailResume.page?orderId="
							+ order.getId())
					.add("first",
							"您好，￥"+desc.getSpec()+"/"+desc.getName()+"项目已上传完成，请及时下载。", "#274084")
					.add("keyword1", WebchatServiceConstant.ORDERCODE+order.getOrdercode(), "#000000")
					.add("keyword2", "已提交", "#F47e2d")
					.add("keyword3",DateUtils.formatDateTime(new Date()), "#000000")
					.add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
					.build();
			System.out.println(tempjson);
			ApiResult result = WxaTemplateUtil.sendtiaonalis(tempjson);
			logger.info("候选人上传简历，推送消息结果="+result);
			//----end send msg
		}
		model.addAttribute("resume", newFileName);
		return "wechat/headhunter/order/resumeconfirm";
	}
	
	/**
	 * 订单详细信息--薪酬分析
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrdetailSalary.do", method = RequestMethod.GET)
	public String myOrdetailSalary(HttpServletRequest request, Model model,int orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
//		openId="o852Is3NXW-0ns6b4e9lzl-6XKbg";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		OrderSalary orderInfo=orderService.getSalaryByOrderId(orderId);
		if(!StringUtils.isEmpty(orderId)){
			orderInfo=orderService.getSalaryByOrderId(orderId);
		}else{
			orderInfo=new OrderSalary();
		}
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		model.addAttribute("resume", orderInfo);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailSalary";
	}
	/**
	 * 订单详细信息--面试辅导
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrdetailInterview.do", method = RequestMethod.GET)
	public String myOrdetailInterview(HttpServletRequest request, Model model,int orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
//		openId="o852Is3NXW-0ns6b4e9lzl-6XKbg";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		OrderInterview orderInfo=null;
		if(!StringUtils.isEmpty(orderId)){
			orderInfo=orderService.getInterviewByOrderId(orderId);
		}else{
			orderInfo=new OrderInterview();
		}
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		model.addAttribute("resume", orderInfo);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailInterview";
	}
	
	/**
	 * 订单详细信息--职业规划
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrdetailPlan.do", method = RequestMethod.GET)
	public String myOrdetailPlan(HttpServletRequest request, Model model,int orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
//		openId="o852Is3NXW-0ns6b4e9lzl-6XKbg";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		OrderPlan orderInfo=null;
		if(!StringUtils.isEmpty(orderId)){
			orderInfo=orderService.getPlanByOrderId(orderId);
		}else{
			orderInfo=new OrderPlan();
		}
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		model.addAttribute("resume", orderInfo);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailPlan";
	}
	
	/**
	 * 订单详细信息--离职咨询
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrdetailLeave.do", method = RequestMethod.GET)
	public String myOrdetailLeave(HttpServletRequest request, Model model,int orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
//		openId="o852Is3NXW-0ns6b4e9lzl-6XKbg";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		OrderLeave orderInfo=null;
		if(!StringUtils.isEmpty(orderId)){
			orderInfo=orderService.getLeaveByOrderId(orderId);
		}else{
			orderInfo=new OrderLeave();
		}
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		model.addAttribute("resume", orderInfo);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailLeave";
	}
	
	@RequestMapping(value = "rs/pdfview.do", method = RequestMethod.GET)
	public void  pdfViewer(HttpServletRequest request, HttpServletResponse response,String urlpath) {
		 logger.info("urlpath="+urlpath);
		  try
	        {
	            InputStream fileInputStream =  getYCFile(urlpath);
	            response.setHeader("Content-Disposition", "attachment;fileName=test.pdf");
	            response.setContentType("multipart/form-data");
	            OutputStream outputStream = response.getOutputStream();
	            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
	        }
	        catch (Exception e)
	        {
	            System.out.println(e.getMessage());
	        }
	}
	public InputStream getYCFile(String urlPath) {  
        InputStream inputStream = null;  
        try {  
            try {  
                String strUrl = urlPath.trim();  
                URL url=new URL(strUrl);
                //打开请求连接
                URLConnection connection = url.openConnection();
                HttpURLConnection httpURLConnection=(HttpURLConnection) connection;
                httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                // 取得输入流，并使用Reader读取
                inputStream = httpURLConnection.getInputStream();
                return inputStream;  
            } catch (IOException e) {  
                System.out.println(e.getMessage());
                inputStream = null;  
            }  
        } catch (Exception e) {  
            System.out.println(e.getMessage());
            inputStream = null;  
        }  
        return inputStream;  
    }
	
	public String orderStatusName(Integer status){
		String statusName=null;
		switch (status) {
	    	case 0:  statusName = "待接单";
	             break;
	    	case 1:  statusName = "进行中";
	             break;
	    	case 2:  statusName = "维权中";
	             break;
	    	case 3:  statusName = "已完成";
	             break;
	    	case 4: statusName = "已取消";
	             break;
	    	case 5: statusName = "已拒单";
	        	break;
	    	case 6: statusName = "已评价";
	    		break;
	    	case 7: statusName = "顾问已确认完成，待您确认";
				break;
	    	
		}
		logger.info("order statusName="+statusName);
		return statusName;
	}
	
	/**
	 * 订单详细信息--简历
	 * @param request
	 * @param model
	 * @param orderId
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/toOrderPriceDiff.do", method = RequestMethod.GET)
	public String myOrdetailPriceDiff(HttpServletRequest request, Model model,Integer orderId) {
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//String openId="o852Is7ih5u1jnXnLaRixmqWn9zk";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Hunter hunter = hunterDAO.getByOpenId(openId);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		// 0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单
		Order order = orderService.getById(orderId);
		order.setStatusName(orderStatusName(order.getStatus()));
		OrderDesc desc=orderService.getOrderDescById(order.getOrdescId());
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
	
		model.addAttribute("order", order);
		model.addAttribute("desc", desc);
		model.addAttribute("emp", emp);
		  /* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		
	      /* */

		return "wechat/headhunter/order/myOrdetailPriceDiff";
	}
	
	
	@OAuthRequired
	@RequestMapping(value = "wechat/order/upPriceDiffdOrder.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> updOrder(HttpServletRequest request, ModelMap model,
			int orderId, int time) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//String openId="o852Is7ih5u1jnXnLaRixmqWn9zk";
		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");
			return returnMap;
		}
		// 编辑更新
		Integer priceDiffMoney=0;
		if(time<=30){
			priceDiffMoney=100;
		}else if(time<=45){
			priceDiffMoney=150;
		}else if(time>45){
			priceDiffMoney=200;
		}else{
			priceDiffMoney=0;
		}
		int res = orderService.updDiffPrice(time,priceDiffMoney, orderId);
		Order order = orderService.getById(orderId);
		OrderDesc desc = orderService.getOrderDescById(order.getOrdescId());
		Hunter hunter = hunterDAO.getById(order.getHunterId());
		Employee employee = employeeDAO.getByEmpId(order.getEmployeeId());
		Person person = null;
		UserInfo userinfo=null;
		if(employee!=null){
			System.out.println("update personid="+employee.getPersonId());
			person=personDAO.getById(employee.getPersonId());
			userinfo=personDAO.getOpenidByUnionid(employee.getPersonId());
		}
		if (res > 0) {
			returnMap.put("errorcode", "0");
			returnMap.put("msg", "已接受该预约咨询服务！");
			// 推送msg于hunter
			String tempjson = TemplateData
					.New()
					.setTouser(openId)
					.setTemplate_id(
							"NRCvt7vthW-aNjQFAkHWA2GIQzpxCOC04VdyNA_7yMc")
					.setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
							+ orderId)
					.add("first",
							"您好,您已提交实际咨询时长，已通知用户"+person.getName()+"预约咨询「" + "￥" + desc.getSpec() + "/"
									+ desc.getName() + "」补足余款,非常感谢！", "#274084")
					.add("keyword1", "YQS" + order.getOrdercode(), "#000000")
					.add("keyword2", "已完成", "#F47e2d")
					.add("keyword3", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()), "#000000")
					.add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情！", "#000000")
					.build();
			ApiResult result = TemplateMsgApi.send(tempjson);
			System.out.println(result);
			
			// 推送msg于candidate
			String tempYRCJson = TemplateData
					.New()
					.setTouser(person.getOpenid())
					.setTemplate_id(
							"TKaDuBl8hbYPVYrPcUBIk5LB3f1N422qxscC088xyIw")
					.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/order/toOrderDetail.do?orderId="
							+ orderId)
					.setMiniprogram(WebchatServiceConstant.APPID_ZHIDAO, "/pages/my-ordetail/my-ordetail?orderId="+orderId)
					.add("first",
							"您好,"+hunter.getName()+"顾问已完成您的预约咨询「" + "￥" + desc.getSpec() + "/"
									+ desc.getName() + "」,服务时长是50分钟，您已超出时长"+time+"分钟，请您补足余款"+priceDiffMoney+"元！", "#274084")
					.add("keyword1", "YQS" + order.getOrdercode(), "#000000")
					.add("keyword2", "补余款", "#F47e2d")
					.add("keyword3", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()), "#000000")
					.add("remark", "如非本人操作，请联系平台客服咨询，点击查看订单详情", "#000000")
					.build();
			ApiResult resultYRC = WxaTemplateUtil.sendtiaonalis(tempYRCJson);
			System.out.println(resultYRC);

		} else {
			returnMap.put("errorcode", "50001");
			returnMap.put("msg", "接受预约咨询信息出错");
		}
		return returnMap;
	}
	
	/**
	 * 虚拟号码拨打
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/order/callPhone.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> callPhone(HttpServletRequest request, ModelMap model,Integer orderId) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Order order=orderService.getById(orderId);
		Employee emp=employeeDAO.getByEmpId(order.getEmployeeId());
		Hunter hunter=hunterDAO.getById(order.getHunterId());
		try {
			String orderTime=order.getOrderTime();
		    //AXB绑定
			 logger.info("失效时间=="+orderTime.subSequence(0, 10)+" "+orderTime.substring(orderTime.length()-5,orderTime.length())+":00");
			 logger.info("PhoneA=" + hunter.getPhone());
			 logger.info("PhoneB=" + emp.getPhone());
			 BindAxbResponse axbResponse = SecretAXB.bindAxb(hunter.getPhone(),emp.getPhone(),orderTime.subSequence(0, 10)+" "+orderTime.substring(orderTime.length()-5,orderTime.length())+":00");
	        logger.info("AXB绑定接口返回的结果----------------");
	        logger.info("Code=" + axbResponse.getCode());
	        logger.info("Message=" + axbResponse.getMessage());
	        logger.info("RequestId=" + axbResponse.getRequestId());
	        String axbSubsId = axbResponse.getSecretBindDTO() == null ? null : axbResponse.getSecretBindDTO().getSubsId();
	        String axbSecretNo = axbResponse.getSecretBindDTO() == null ? null : axbResponse.getSecretBindDTO().getSecretNo();
	        logger.info("subsId=" + axbSubsId);
	        logger.info("secretNo=" + axbSecretNo);
	
	        //预留一分钟给您做拨打测试
			Thread.sleep(60000L);
	
	        if (axbResponse.getCode() != null && axbResponse.getCode().equals("OK")) {
	            UnbindSubscriptionResponse unbind = SecretAXB.unbind(axbSubsId, axbSecretNo);
	            logger.info("解绑接口返回数据AXB----------------");
	            logger.info("Code=" + unbind.getCode());
	            logger.info("Message=" + unbind.getMessage());
	            logger.info("RequestId=" + unbind.getRequestId());
	            
	            returnMap.put("errorcode", "0");
				returnMap.put("msg", axbResponse.getMessage());
	        }else{
	        	returnMap.put("errorcode", axbResponse.getCode());
				returnMap.put("msg", axbResponse.getMessage());
	        }

		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnMap;

	}
	
}
